﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Dto.LS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Service
{
    public class VisuallargeScreenService : BaseService, IVisuallargeScreenService
    {
        private readonly IReceivingOrderDetailRepository _receivingOrderDetailRepository;
        private readonly IReceivingBillRepository _receivingBillRepository;
        private readonly IShippingOrderDetailRepository _shippingOrderDetailRepository;
        private readonly ITransferBinOrderRepository _transferBinOrderRepository;
        private readonly IStocktakingOrderRepository _stocktakingOrderRepository;
        private readonly IShippingLockCellRepository _shippingLockCellRepository;
        private readonly IMaterialCategoryRepository _materialCategoryRepository;
        private readonly IMaterialGroupRepository _materialGroupRepository;
        private readonly IInventoryRepository _inventoryRepository;
        private readonly IMaterialRepository _materialRepository;
        private readonly IReceivingBillDetailRepository _receivingBillDetailRepository;
        private readonly IWarehouseRepository _warehouseRepository;
        private readonly ICellRepository _cellRepository;

        public VisuallargeScreenService(
            IMapper mapper,
            IReceivingOrderDetailRepository _receivingOrderDetailRepository,
            IShippingOrderDetailRepository _shippingOrderDetailRepository,
            ITransferBinOrderRepository _transferBinOrderRepository,
            IStocktakingOrderRepository _stocktakingOrderRepository,
            IInventoryRepository _inventoryRepository,
            IShippingLockCellRepository _shippingLockCellRepository,
            IMaterialCategoryRepository _materialCategoryRepository,
            IMaterialGroupRepository _materialGroupRepository,
            IMaterialRepository _materialRepository,
            IReceivingBillRepository _receivingBillRepository,
            IReceivingBillDetailRepository _receivingBillDetailRepository,
            IWarehouseRepository _warehouseRepository,
            ICellRepository _cellRepository

            ) : base(mapper)
        {
            this._receivingOrderDetailRepository = _receivingOrderDetailRepository;
            this._shippingOrderDetailRepository = _shippingOrderDetailRepository;
            this._transferBinOrderRepository = _transferBinOrderRepository;
            this._stocktakingOrderRepository = _stocktakingOrderRepository;
            this._shippingLockCellRepository = _shippingLockCellRepository;
            this._materialCategoryRepository = _materialCategoryRepository;
            this._materialGroupRepository = _materialGroupRepository;
            this._inventoryRepository = _inventoryRepository;
            this._materialRepository = _materialRepository;
            this._receivingBillRepository = _receivingBillRepository;
            this._receivingBillDetailRepository = _receivingBillDetailRepository;
            this._warehouseRepository = _warehouseRepository;
            this._cellRepository = _cellRepository;

        }

        /// <summary>
        /// 待办已办任务统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="type"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<ToDoDoneDto> GetToDoDone(int pageIndex, int pageSize, int type, out int totalCount)
        {
            List<ToDoDoneDto> AllList = new List<ToDoDoneDto>();
            //待办
            if (type == 1)
            {
                //查看所有状态不为已完成的入库单明细并且根据订单号排重
                var ReceivingList = _receivingOrderDetailRepository.GetEntityWhereAll(x => x.Status != 3).AsEnumerable().DistinctBy(x => x.OrderSn).ToList();
                foreach (var Receiving in ReceivingList)
                {

                    ToDoDoneDto toDoDoneDto = new ToDoDoneDto()
                    {
                        OrderSn = Receiving.OrderSn,
                        type = 1,
                        CreateTime = Receiving.CreateDate,
                        materialCode = Receiving.MaterialCode,
                        materialName = Receiving.MaterialName,
                        qty = (decimal)Receiving.Qty,
                        warnType = (int)Receiving.BillType

                    };
                    AllList.Add(toDoDoneDto);
                }
                //查看所有状态不为已完成的出库单明细并且根据订单号排重
                var ShippingList = _shippingOrderDetailRepository.GetEntityWhereAll(x => x.Status != 4).AsEnumerable().DistinctBy(x => x.OrderSn).ToList();
                foreach (var Shipping in ShippingList)
                {
                    ToDoDoneDto toDoDoneDto = new ToDoDoneDto()
                    {
                        OrderSn = Shipping.OrderSn,
                        type = 2,
                        CreateTime = Shipping.CreateDate,
                        materialName = Shipping.MaterialName,
                        materialCode = Shipping.MaterialCode,
                        qty = (decimal)Shipping.Qty,
                        warnType = (int)Shipping.BillType
                    };
                    AllList.Add(toDoDoneDto);
                }
                //查看所有状态不为已完成 的移库单并且根据订单号排重
                var TransferBinList = _transferBinOrderRepository.GetEntityWhereAll(x => x.Status != 4).AsEnumerable().DistinctBy(x => x.OrderSn).ToList();
                foreach (var TransferBin in TransferBinList)
                {
                    ToDoDoneDto toDoDoneDto = new ToDoDoneDto()
                    {
                        OrderSn = TransferBin.OrderSn,
                        type = 3,
                        CreateTime = TransferBin.CreateDate

                    };
                    AllList.Add(toDoDoneDto);
                }
                //查看所有状态不为已完成的盘点单并且根据订单号排重
                var StocktakingList = _stocktakingOrderRepository.GetEntityWhereAll(x => x.Status != 4).AsEnumerable().DistinctBy(x => x.OrderSn).ToList();
                foreach (var Stocktaking in StocktakingList)
                {
                    ToDoDoneDto toDoDoneDto = new ToDoDoneDto()
                    {
                        OrderSn = Stocktaking.OrderSn,
                        type = 4,
                        CreateTime = Stocktaking.CreateDate
                    };
                    AllList.Add(toDoDoneDto);
                }
                totalCount = AllList.Count();
                return AllList.OrderByDescending(x => x.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            //已办
            else if (type == 2)
            {
                //查看所有状态为已完成的入库单明细并且根据订单号排重
                var ReceivingList = _receivingOrderDetailRepository.GetEntityWhereAll(x => x.Status == 3).AsEnumerable().DistinctBy(x => x.OrderSn).ToList();
                foreach (var Receiving in ReceivingList)
                {
                    ToDoDoneDto toDoDoneDto = new ToDoDoneDto()
                    {
                        OrderSn = Receiving.OrderSn,
                        type = 1,
                        CreateTime = Receiving.CreateDate,
                        materialCode = Receiving.MaterialCode,
                        materialName = Receiving.MaterialName,
                        qty = (decimal)Receiving.Qty,
                        warnType = (int)Receiving.BillType
                    };
                    AllList.Add(toDoDoneDto);
                }
                //查看所有状态为已完成的出库单明细并且根据订单号排重
                var ShippingList = _shippingOrderDetailRepository.GetEntityWhereAll(d => d.Status == 4).AsEnumerable().DistinctBy(d => d.OrderSn).ToList();
                foreach (var Shipping in ShippingList)
                {
                    ToDoDoneDto toDoDoneDto = new ToDoDoneDto()
                    {
                        OrderSn = Shipping.OrderSn,
                        type = 2,
                        CreateTime = Shipping.CreateDate,
                        materialCode = Shipping.MaterialCode,
                        materialName = Shipping.MaterialName,
                        qty = (decimal)Shipping.Qty,
                        warnType = (int)Shipping.BillType
                    };
                    AllList.Add(toDoDoneDto);
                }
                //查看所有状态为已完成 的移库单并且根据订单号排重
                var TransferBinList = _transferBinOrderRepository.GetEntityWhereAll(d => d.Status == 4).AsEnumerable().DistinctBy(d => d.OrderSn).ToList();
                foreach (var TransferBin in TransferBinList)
                {
                    ToDoDoneDto toDoDoneDto = new ToDoDoneDto()
                    {
                        OrderSn = TransferBin.OrderSn,
                        type = 3,
                        CreateTime = TransferBin.CreateDate,
                    };
                    AllList.Add(toDoDoneDto);
                }
                //查看所有状态为已完成的盘点单并且根据订单号排重
                var StocktakingList = _stocktakingOrderRepository.GetEntityWhereAll(d => d.Status == 4).AsEnumerable().DistinctBy(d => d.OrderSn).ToList();
                foreach (var Stocktaking in StocktakingList)
                {
                    ToDoDoneDto toDoDoneDto = new ToDoDoneDto()
                    {
                        OrderSn = Stocktaking.OrderSn,
                        type = 4,
                        CreateTime = Stocktaking.CreateDate,
                    };
                    AllList.Add(toDoDoneDto);
                }
                totalCount = AllList.Count();
                return AllList.OrderByDescending(x => x.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (type == 5)
            {
                //获取所有物料的信息
                var mlist = _materialRepository.GetEntityAlls();
                int? minsafetystock = 0;
                List<ToDoDoneDto> toDoDoneDto = new List<ToDoDoneDto>();
                //查找状态为正常库存的和未锁定的和库区编码为B01的所有信息
                var ilist = _inventoryRepository.GetEntityAlls().Where(d => d.Status == 1 && d.IsLock == false && d.AreaCode == "B01").ToList();
                foreach (var item in ilist)
                {
                    ToDoDoneDto toDoDone = new ToDoDoneDto();
                    //查找mlist的第一个值，如果找到返回它的MinSafetyStock(最小安全数)没有返回null
                    minsafetystock = mlist.FirstOrDefault(d => d.Id == item.MaterialId)?.MinSafetyStock;
                    //如果可用数量<=最小安全数
                    if (item.AvailableQty <= minsafetystock)
                    {
                        toDoDone.materialCode = item.MaterialCode;
                        toDoDone.materialName = item.MaterialName;
                        toDoDone.qty = (decimal)item.AvailableQty;
                        toDoDone.warnType = 1;
                        toDoDone.name = "物料" + item.MaterialName + "最小库存数量" + minsafetystock + ",当前数量:" + item.AvailableQty;
                        toDoDoneDto.Add(toDoDone);
                    }
                }
                totalCount = toDoDoneDto.Count();
                return toDoDoneDto.OrderByDescending(x => x.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                totalCount = 0;
                return null;
            }

        }
        /// <summary>
        /// 月出入移盘统计
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public EntryAndExitTransferStatisticsDto GetAllQty()
        {
            var startDate = DateTime.Today.AddDays(-30);//从30天前开始计算
            var enDate = DateTime.Today;//当天
            EntryAndExitTransferStatisticsDto dto = new EntryAndExitTransferStatisticsDto();
            //入库单详情数量
            #region  以前的写法
            //var ReceivingList = _receivingOrderDetailRepository.GetEntityAlls().AsEnumerable().DistinctBy(d => d.OrderSn);
            //var ReceivingListCount = ReceivingList.Where(d => d.CreateDate >= startDate && d.CreateDate <= enDate);
            #endregion
            dto.ReceivingQty = _receivingOrderDetailRepository.GetEntityAlls().AsEnumerable().DistinctBy(d => d.OrderSn).Where(d => d.CreateDate >= startDate && d.CreateDate <= enDate).Count();
            //出库数量
            dto.ShippingQty = _shippingOrderDetailRepository.GetEntityAlls().AsEnumerable().DistinctBy(d => d.OrderSn).Where(d => d.CreateDate >= startDate && d.CreateDate <= enDate).Count();
            //移库数量
            dto.TransferBinQty = _transferBinOrderRepository.GetEntityAlls().AsEnumerable().DistinctBy(d => d.OrderSn).Where(d => d.CreateDate >= startDate && d.CreateDate <= enDate).Count();
            //盘库数量
            dto.StocktakingQty = _stocktakingOrderRepository.GetEntityAlls().AsEnumerable().DistinctBy(d => d.OrderSn).Where(d => d.CreateDate >= startDate && d.CreateDate <= enDate).Count();
            return dto;
        }
        /// <summary>
        /// 获取库存总数
        /// </summary>
        /// <returns></returns>
        public InventoryQtyDto GetInventoryQty()
        {
            InventoryQtyDto dto = new InventoryQtyDto();
            //查看库存表里所有的可用库存数量
            var InventoryQtyNum = _inventoryRepository.GetEntityAll().Sum(d => d.AvailableQty);
            dto.InventoryQty = (int)InventoryQtyNum;
            var inventoryList = _inventoryRepository.GetAllEntityList();
            foreach (var item in inventoryList)
            {
                int qtyPrice = 0;
                if (item.Price.HasValue)
                {
                    qtyPrice = (int)(item.AvailableQty * item.Price);
                }
                dto.UseInventoryQty = dto.UseInventoryQty += qtyPrice;
            }
            //根据库存表里的质量状态为0（待检）为1（合格） 进行查询在根据物品分类表的Id进行分组，然后取到每个组的第一个并计数    总结：拿到符合状态下的不同物料组的数目  
            var GoodProductQtyNum = _inventoryRepository.GetEntityWhereAll(d => d.QualityState == 0 || d.QualityState == 1).GroupBy(d => d.MaterialCategoryId).Select(d => d.First()).ToList();
            dto.GoodProductQty = GoodProductQtyNum.Count();
            #region  原来的非良品数量统计
            //var NotGoodProductNum = _inventoryRepository.GetEntityAll().GroupBy(x => x.MaterialName).Select(group => group.First()).ToList();
            //dto.NotGoodProductQty = NotGoodProductNum.Count();
            #endregion
            //根据库存表里的质量状态为0（待检）为1（合格） 进行查询在根据物品分类表的Id进行分组，然后取到每个组的第一个并计数    总结：拿到符合状态下的不同物料组的数目 
            var NotGoodProductNum = _inventoryRepository.GetEntityWhereAll(d => d.QualityState == 2).GroupBy(d => d.MaterialCategoryId).Select(d => d.First()).ToList();
            dto.NotGoodProductQty = NotGoodProductNum.Count();
            return dto;
        }
        /// <summary>
        /// 根据质量等级查询
        /// </summary>
        /// <returns></returns>
        public List<QualityStateDto> GetQtyByQualityState()
        {
            List<QualityStateDto> qualityStateDtos = new List<QualityStateDto>();

            var inventoryQty = _inventoryRepository.GetEntityAll()
                .GroupBy(x => x.QualityState)
                .Select(group => new QualityStateDto
                {
                    name = group.Key,
                    value = (int)group.Sum(x => x.AvailableQty)
                })
                .ToList();

            qualityStateDtos.AddRange(inventoryQty);

            return qualityStateDtos;
        }
        /// <summary>
        /// 出入库数量统计
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public List<AppointDateQtyDto> GetQtyByWork(string StartTime, string EndTime)
        {
            DateTime startDateTime = DateTime.Parse(StartTime);
            DateTime endDateTime = DateTime.Parse(EndTime).AddDays(1); // 结束时间需要加一天，以包含该天的数据

            List<AppointDateQtyDto> appointDateQtyDtos = new List<AppointDateQtyDto>();
            //查询指定时间范围内的出入库单明细的时间
            var ReceivingList = _receivingOrderDetailRepository.GetEntityWhereAll(x => x.CreateDate >= startDateTime && x.CreateDate <= endDateTime)
                  .GroupBy(x => x.CreateDate.Date)
                  .Select(data => new AppointDateQtyDto
                  {
                      DateTime = data.Key,
                      ReceivingQty = (int)data.Sum(x => x.Qty),
                      ShippingQty = 0
                  })
                  .ToList();

            var ShippingList = _shippingOrderDetailRepository.GetEntityWhereAll(x => x.CreateDate >= startDateTime && x.CreateDate <= endDateTime)
               .AsEnumerable()
               .GroupBy(x => x.CreateDate.Date)
               .Select(data => new AppointDateQtyDto
               {
                   DateTime = data.Key,
                   ShippingQty = (int)_shippingLockCellRepository.QueryEntityWhere(x => x.OrderDetailId == data.First().Id).OutQty,
                   ReceivingQty = 0
               })
               .ToList();
            var groupedResult = ReceivingList.Concat(ShippingList)
            //合并两表
            .GroupBy(d => d.DateTime)
            .Select(d => new AppointDateQtyDto
            {
                DateTime = d.Key,
                ReceivingQty = d.Sum(d => d.ReceivingQty),//计算入库数量的总和
                ShippingQty = d.Sum(d => d.ShippingQty)//计算出库数据的总和
            }).ToList();
            return groupedResult;
        }
        /// <summary>
        /// 按装备大类统计
        /// </summary>
        /// <returns></returns>
        public List<MaterialCategoryGroup> GetMaterialCategoryQty()
        {
            var allInventory = _inventoryRepository.GetAllEntityList();
            var materialCategoryGroups = allInventory
                .GroupBy(d => d.MaterialTypeName)
                .Select(d => new MaterialCategoryGroup
                {
                    MaterialCategoryType = d.Key,
                    Qty = d.Sum(d => d.AvailableQty) ?? 0
                }).ToList();
            return materialCategoryGroups;
        }
        /// <summary>
        /// 按装备大类统计
        /// </summary>
        /// <returns></returns>
        public List<MaterialGroups> GetMaterialGroupsQty()
        {
            List<MaterialGroups> materialGroups = new List<MaterialGroups>();

            // 获取所有的 MaterialGroup 信息到内存中
            var materialGroupsFromRepo = _materialGroupRepository.GetEntityAll().ToList();

            // 获取库存数据并进行分组
            var inventoryQty = _inventoryRepository.GetEntityAll()
                .AsEnumerable()  // 强制使用内存中的数据进行操作
                .GroupBy(x => x.MaterialTypeName)
                .Select(group => new MaterialGroups
                {
                    MaterialGroupsCode = group.Key,
                    Qty = (int)group.Sum(x => x.AvailableQty),
                    // 使用 FirstOrDefault 从内存中的数据获取 MaterialGroupName
                    MaterialGroupName = materialGroupsFromRepo
                        .FirstOrDefault(x => x.Code == group.Key)?.Name
                })
                .ToList();

            materialGroups.AddRange(inventoryQty);

            return materialGroups;
        }
        public string GetUSBPath()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 大屏调拨/自购入库查询
        /// </summary>
        /// <returns></returns>
        public List<MaterialTypeCountDto> GetMaterialTypeCount()
        {
            var list = _receivingBillDetailRepository.GetAllEntityList();
            List<MaterialTypeCountDto> materialTypeCountDtos = new List<MaterialTypeCountDto>();

            var invobjcount = _inventoryRepository.GetEntityAll().GroupBy(d => d.MaterialTypeName).Count();
            MaterialTypeCountDto materialTypeCount = new MaterialTypeCountDto();
            materialTypeCount.materialType = 1;
            materialTypeCount.count = 0;
            materialTypeCountDtos.Add(materialTypeCount);


            MaterialTypeCountDto materialType = new MaterialTypeCountDto();
            materialType.materialType = 2;
            materialType.count = invobjcount;
            materialTypeCountDtos.Add(materialType);

            return materialTypeCountDtos;
        }
        /// <summary>
        /// 入库
        /// </summary>
        /// <returns></returns>
        public List<EquipmentReceivingDto> GetEquipmentReceiving()
        {
            List<EquipmentReceivingDto> equipmentReceivingDtos = new List<EquipmentReceivingDto>();
            var startOfToday = DateTime.Today; // 今天的开始时间
            var endOfToday = DateTime.Today.AddDays(1).AddTicks(-1); // 今天的结束时间

            var relist = _receivingOrderDetailRepository.GetEntityWhereAll(x => x.CreateDate >= startOfToday && x.CreateDate <= endOfToday);

            foreach (var item in relist)
            {
                EquipmentReceivingDto equipmentReceivingDto = new EquipmentReceivingDto();
                equipmentReceivingDto.Name = item.MaterialName;
                equipmentReceivingDto.Qty = item.Qty ?? 0;
                equipmentReceivingDtos.Add(equipmentReceivingDto);
            }
            return equipmentReceivingDtos;


        }
        /// <summary>
        /// 出库
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<EquipmentShippingDto> GetEquipmentShipping()
        {
            List<EquipmentShippingDto> equipmentShippingDtos = new List<EquipmentShippingDto>();
            var startOfToday = DateTime.Today;
            var endOfToday = DateTime.Today.AddDays(1).AddTicks(-1);//今天结束时间
            var shipplist = _shippingLockCellRepository.GetEntityWhereAll(d => d.CreateDate >= startOfToday && d.CreateDate <= endOfToday);
            foreach (var item in shipplist)
            {
                EquipmentShippingDto equipmentShippingDto = new EquipmentShippingDto()
                {
                    Name = item.MaterialName,
                    Qty = item.OutQty ?? 0,

                };
                equipmentShippingDtos.Add(equipmentShippingDto);

            }
            return equipmentShippingDtos;
        }
        /// <summary>
        /// 今日数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TodayDataDto> GetTodayData()
        {
            List<TodayDataDto> todayDataDtos = new List<TodayDataDto>();
            var today = DateTime.Today;

            //入库单量
            var receivingList = _receivingBillRepository.GetEntityWhereAll(d => d.CreateDate >= today && d.CreateDate < today.AddDays(1));
            TodayDataDto receivingListQty = new TodayDataDto()
            {
                Name = "入库单量",
                Num = receivingList.Count()
            };
            todayDataDtos.Add(receivingListQty);
            //入库货量
            var receivingDetailList = _receivingBillDetailRepository.GetEntityWhereAll(d => d.CreateDate >= today && d.CreateDate < today.AddDays(1));
            TodayDataDto receivingGoodsQty = new TodayDataDto()
            {
                Name = "入库货量",
                Num = (int)receivingDetailList.Sum(d => d.ReceivedQty)
            };
            todayDataDtos.Add(receivingGoodsQty);
            //未完成入库
            var receivingStatusList = _receivingBillRepository.GetEntityWhereAll(d => d.Status != 2 && d.CreateDate >= today && d.CreateDate < today.AddDays(1));
            TodayDataDto IncompleteQty = new TodayDataDto()
            {
                Name = "未完成入库",
                Num = receivingStatusList.Count()
            };
            todayDataDtos.Add(IncompleteQty);
            //出库单量
            var shippingQty = _shippingOrderDetailRepository.GetEntityWhereAll(d => d.CreateDate >= today && d.CreateDate < today.AddDays(1));
            TodayDataDto shippingListQty = new TodayDataDto()
            {
                Name = "出库单量",
                Num = shippingQty.Count()
            };
            todayDataDtos.Add(shippingListQty);
            //出库货量
            TodayDataDto shippingGoodsQty = new TodayDataDto()
            {
                Name = "出库货量",
                Num = (int)shippingQty.Sum(d => d.ShippedQty)
            };
            todayDataDtos.Add(shippingGoodsQty);
            //未完成出库
            TodayDataDto IncompleteShippingQty = new TodayDataDto()
            {
                Name = "未完成出库",
                Num = shippingQty.Where(d => d.Status != 4).Count()
            };
            todayDataDtos.Add(shippingGoodsQty);


            return todayDataDtos;
        }
        /// <summary>
        /// 获取7天数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TodayDataDto> GetSevenData()
        {

            return GetShippingReceivingMsg(7);
        }
        /// <summary> 
        /// 获取近31天的数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TodayDataDto> GetThirtyOneData()
        {
            return GetShippingReceivingMsg(31);
        }

        /// <summary>
        /// 分装方法
        /// </summary>
        /// <param name="day">天数</param>
        /// <returns></returns>
        private List<TodayDataDto> GetShippingReceivingMsg(int day)
        {
            List<TodayDataDto> todayDataDtos = new List<TodayDataDto>();
            var today = DateTime.Today;
            var DaysAgo = today.AddDays(-day);
            //入库单量
            var receivingList = _receivingBillRepository.GetEntityWhereAll(x => x.CreateDate >= DaysAgo && x.CreateDate < today.AddDays(1));
            TodayDataDto receivingListQty = new TodayDataDto();
            receivingListQty.Name = "入库单量";
            receivingListQty.Num = receivingList.Count();
            todayDataDtos.Add(receivingListQty);

            //入库货量
            var receivingDetailList = _receivingBillDetailRepository.GetEntityWhereAll(x => x.CreateDate >= DaysAgo && x.CreateDate < today.AddDays(1));
            TodayDataDto receivingGoodsQty = new TodayDataDto();
            receivingGoodsQty.Name = "入库货量";
            receivingGoodsQty.Num = (int)receivingDetailList.Sum(x => x.ReceivedQty);
            todayDataDtos.Add(receivingGoodsQty);

            //出库单量
            var shippingList = _shippingOrderDetailRepository.GetEntityWhereAll(x => x.CreateDate >= DaysAgo && x.CreateDate < today.AddDays(1));
            TodayDataDto shippingListQty = new TodayDataDto();
            shippingListQty.Name = "出库单量";
            shippingListQty.Num = shippingList.Count();
            todayDataDtos.Add(shippingListQty);

            //出库货量
            var shippingDetailList = _shippingOrderDetailRepository.GetEntityWhereAll(x => x.CreateDate >= DaysAgo && x.CreateDate < today.AddDays(1));
            TodayDataDto shippingGoodsQty = new TodayDataDto();
            shippingGoodsQty.Name = "出库货量";
            shippingGoodsQty.Num = (int)shippingDetailList.Sum(x => x.ShippedQty);
            todayDataDtos.Add(shippingGoodsQty);

            return todayDataDtos;
        }
        /// <summary>
        /// 库房相关
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<WarehouseRelatedDto> GetWarehouseMsg()
        {
            List<WarehouseRelatedDto> warehouseRelatedDtos = new List<WarehouseRelatedDto>();
            var warehouseList = _warehouseRepository.GetAllEntityList();
            foreach (var item in warehouseList)
            {
                WarehouseRelatedDto warehouseRelatedDto = new WarehouseRelatedDto();
                warehouseRelatedDto.WarehouseName = item.Name;
                var inventoryList = _inventoryRepository.GetEntityWhereAll(x => x.WarehouseId == item.Id); ;
                warehouseRelatedDto.RelaTimeInventory = (int)inventoryList.Sum(x => x.AvailableQty);
                var shippingList = _shippingLockCellRepository.GetEntityWhereAll(x => x.WhId == item.Id);
                warehouseRelatedDto.TotalShipmentQty = (int)shippingList.Sum(x => x.OutQty);
                var receivingList = _receivingBillRepository.GetEntityWhereAll(x => x.Status == 2 && x.WarehouseId == item.Id);
                //月均发货时效

                var receivingFinish = _receivingBillRepository.GetEntityWhereAll(x => x.CreateDate.Month == DateTime.Now.Month && x.WarehouseId == item.Id);
                var finishOrder = receivingFinish.Where(x => x.Status == 2);
                var notFinishOrder = receivingFinish.Where(x => x.Status != 2);
                int totalOrders = receivingFinish.Count();
                int completedOrders = finishOrder.Count();
                double completionRate = totalOrders > 0 ? (completedOrders / (double)totalOrders) * 100 : 0;
                warehouseRelatedDto.FulfillmentRate = completionRate.ToString("F2") + "%";
                warehouseRelatedDto.DeliveryTime = DateTime.Now.ToString("yyyy-MM-dd");

                warehouseRelatedDtos.Add(warehouseRelatedDto);
                //EIQ(EIQ)

            }
            return warehouseRelatedDtos;
        }
        /// <summary>
        /// SKU
        /// </summary>
        /// <returns></returns>
        public List<SKUDto> GetSKUMsg()
        {
            List<SKUDto> skuDtos = new List<SKUDto>();
            var warehouseList = _warehouseRepository.GetAllEntityList();
            foreach (var item in warehouseList)
            {
                var inventoryList = _inventoryRepository.GetEntityWhereAll(x => x.WarehouseId == item.Id);
                SKUDto sKUDto = new SKUDto();
                sKUDto.Name = item.Name;
                decimal number = 0;
                if (inventoryList.Sum(x => x.AvailableQty) != 0)
                {
                    number = (decimal)inventoryList.Sum(x => x.AvailableQty);
                }
                sKUDto.Num = number;
                skuDtos.Add(sKUDto);
            }


            return skuDtos;
        }
        /// <summary>
        /// 仓库利用率
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<WarehoustUtilizationRateDto> GetWarehoustUtilization()
        {
            List<WarehoustUtilizationRateDto> warehoustUtilizationRateDtos = new List<WarehoustUtilizationRateDto>();
            var warehouseList = _warehouseRepository.GetAllEntityList();
            foreach (var item in warehouseList)
            {
                WarehoustUtilizationRateDto warehoustUtilizationRateDto = new WarehoustUtilizationRateDto();
                //根据库房Id查询仓位表的信息
                var cellList = _cellRepository.GetEntityWhereAll(x => x.WhId == item.Id);
                warehoustUtilizationRateDto.Name = item.Name;
                WarehoustUtilizationRateChildDto warehoustUtilizationRateChildDto = new WarehoustUtilizationRateChildDto();
                //查询满仓状态为空仓和未被锁定的仓位的信息数量
                var nullCount = cellList.Where(x => x.FullStatus == 0 && x.IsLock == false).Count();
                warehoustUtilizationRateChildDto.CellAllCount = cellList.Count();
                warehoustUtilizationRateChildDto.NullCellCount = nullCount;
                var num = ((double)nullCount / cellList.Count() * 100);
                warehoustUtilizationRateChildDto.NullCellProportion = num.ToString("F2")/* + "%" */;
                warehoustUtilizationRateDto.Child.Add(warehoustUtilizationRateChildDto);
                warehoustUtilizationRateDtos.Add(warehoustUtilizationRateDto);
            }
            return warehoustUtilizationRateDtos;
        }
        /// <summary>
        /// 近30天仓库单量的走势
        /// </summary>
        /// <returns></returns>

        public List<WarehouseTrend> GetWarehouseTrend()
        {
            List<WarehouseTrend> warehouseTrends = new List<WarehouseTrend>();
            var today = DateTime.Today;
            for (int i = 0; i < 31; i++)
            {
                var DaysAgo = today.AddDays(-i);
                WarehouseTrend warehouseTrend = new WarehouseTrend();
                warehouseTrend.Days = DaysAgo.ToString("MM-dd");
                var shippingList = _shippingLockCellRepository.GetAllEntityList().ToList();
                shippingList = shippingList.Where(d => d.CreateDate.Date == DaysAgo.Date).ToList();
                warehouseTrend.Qty = shippingList.Count();
                warehouseTrends.Add(warehouseTrend);
            }
            return warehouseTrends;
        }
        /// <summary>
        /// 近30天仓库出货量
        /// </summary>
        /// <returns></returns>
        public List<WarehouseShippingDto> GetWarehouseShippingQty()
        {
            List<WarehouseShippingDto> warehouseShippings = new List<WarehouseShippingDto>();
            var today = DateTime.Today;
            var warehouseList = _warehouseRepository.GetAllEntityList().ToList();
            foreach (var item in warehouseList)
            {
                int shipingQty = 0;
                WarehouseShippingDto warehouseShipping = new WarehouseShippingDto();
                warehouseShipping.WarehouseName = item.Name;
                for (int i = 0; i < 31; i++)
                {
                    var DaysAgo = today.AddDays(-i);
                    var shippingList = _shippingLockCellRepository.GetAllEntityList();
                    shippingList = shippingList.Where(d => d.CreateDate.Date == DaysAgo.Date && d.WhId == item.Id).ToList();

                }
                warehouseShipping.Qty = shipingQty;
                warehouseShippings.Add(warehouseShipping);
            }
            return warehouseShippings;
        }
        /// <summary>
        /// 实时库存
        /// </summary>
        /// <returns></returns>

        public List<InventoryDto> GetInventory()
        {
            List<InventoryDto> inventoryDtos = new List<InventoryDto>();
            var allInventoryList = _inventoryRepository.GetAllEntityList().GroupBy(d => d.MaterialName).ToList();
            foreach (var item in allInventoryList)
            {
                InventoryDto inventoryDto = new InventoryDto();
                var firstItem = item.First();
                inventoryDto.MaterialCode = firstItem.MaterialCode;
                inventoryDto.MaterialName = firstItem.MaterialName;
                //inventoryDto.Qty = (decimal)item.Sum(d => d.AvailableQty) == 0 ? 0 : (decimal)item.Sum(d => d.AvailableQty);
                var totalQty = item.Sum(x => x.AvailableQty) ?? 0;
                inventoryDto.Qty = totalQty;

                inventoryDtos.Add(inventoryDto);
            }

            return inventoryDtos;
        }
    }
}
